package aop

import (
	"log"
	"math"
)

const MaxIndex = math.MaxInt8 / 2

type Content struct {
	Code string `json:"code"`
	Msg  string `json:"msg"`
}

type Context struct {
	currentIndex int8
	handleChans  []func(*Context)
}

func newContext(size int) *Context {
	return &Context{
		currentIndex: -1,
		handleChans:  make([]func(*Context), 0, size),
	}
}

func (c *Context) appendHandle(handle func(*Context)) {
	c.handleChans = append(c.handleChans, handle)
}

func (c *Context) Next() {
	if c.currentIndex < MaxIndex {
		c.currentIndex++ //中间件嵌套
		length := int8(len(c.handleChans))
		for ; c.currentIndex < length; c.currentIndex++ { //同级中间件运行
			if !c.isAbort() {
				c.handleChans[c.currentIndex](c)
			} else {
				return
			}
		}
	}
}

func (c *Context) Abort() {
	c.currentIndex = MaxIndex
	log.Printf("handle was aborted...")
}

func (c *Context) isAbort() bool {
	return c.currentIndex == MaxIndex
}

func (c *Context) reset() {
	c.currentIndex = -1
	c.handleChans = c.handleChans[:0]
}
